import style from './index.module.scss'
import logo from 'assets/logo.png'
import React, { Component } from 'react'
import { userLogin } from 'api/user';
import { Card, Button, Checkbox, Form, Input, message } from 'antd';
import { setToken } from 'utils/storage';
export default class Login extends Component {
  state = {
    loading: false
  }
  render() {
    // console.log(style);
    return (
      <div className={style.login}>
        <Card className='login-container'>
          <img src={logo} alt="" className='login-logo' />
          {/* form表单 */}
          <Form onFinish={this.onFinish} initialValues={{ mobile: '13911111111', code: '246810', agree: true }}>
            <Form.Item name='mobile' rules={
              [
                { required: true, message: '手机号不能为空' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }
              ]
            }>
              <Input size='large' placeholder='请输入账号' autoComplete='off' />
            </Form.Item>

            <Form.Item name='code' rules={
              [
                { required: true, message: '验证码不能为空' },
                { pattern: /^\d{6}$/, message: '验证码格式错误' }
              ]
            }>
              <Input size='large' placeholder='请输入验证码' autoComplete='off' />
            </Form.Item>

            <Form.Item valuePropName='checked' name='agree' rules={
              [
                {
                  // 自定义校验
                  validator: (rule, value) => {
                    if (value) {
                      return Promise.resolve()
                    } else {
                      return Promise.reject(new Error('请阅读并同意[用户协议]'))
                    }
                  }
                }
              ]
            } >
              <Checkbox>我已阅读并同意[用户协议]</Checkbox>
            </Form.Item>

            <Form.Item
            >
              <Button block size='large' type="primary" htmlType="submit" loading={this.state.loading}>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  // 获取表单数据，表单提供的onChange事件
  onFinish = async ({ mobile, code }) => {
    this.setState({
      loading: true
    })
    try {
      const { data } = await userLogin(mobile, code)
      // 登录成功之后
      // 3、消息提示
      // alert('登录成功')
      message.success('登录成功', 1, () => {
        // 1、保存token
        // window.localStorage.setItem('token', data.data.token)
        setToken(data.token)
        // 2、跳转到首页
        const { state } = this.props.location
        if (state) {
          this.props.history.push(state.from)
        } else {
          this.props.history.push('/home')
        }
      })
    } catch (error) {
      message.error(error.response.data.message, 1)
      this.setState({
        loading: false
      })
    }
  }
}
